package com.tbit.uqbike.service.business.impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tbit.uqbike.enums.SystemCodeEnum;
import com.tbit.uqbike.manager.exception.BaseException;
import com.tbit.uqbike.object.pojo.Account;
import com.tbit.uqbike.object.pojo.Coupon;
import com.tbit.uqbike.object.pojo.RechargeConfig;
import com.tbit.uqbike.object.pojo.RechargeGive;
import com.tbit.uqbike.object.pojo.dto.RechargeConfigDTO;
import com.tbit.uqbike.object.pojo.vo.RechargeConfigVO;
import com.tbit.uqbike.object.value.LoginInfo;
import com.tbit.common.entity.view.Result;
import com.tbit.uqbike.service.business.CouponService;
import com.tbit.uqbike.service.business.RechargeConfigService;
import com.tbit.uqbike.service.rpcservice.PurviewService;
import com.tbit.uqbike.webmanager.dao.core.AccountDao;
import com.tbit.uqbike.webmanager.dao.core.RechargeConfigDao;
import com.tbit.uqbike.webmanager.dao.core.RechargeGiveDao;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author: chen
 * @Description: 充值信息配置
 * @Date: 创建于 11:12 2020/5/8
 */
@Service
public class RechargeConfigServiceImpl implements RechargeConfigService {
    @Autowired
    private CouponService couponService;
    @Resource
    private RechargeConfigDao rechargeConfigDao;
    @Resource
    private AccountDao accountDao;
    @Resource
    private RechargeGiveDao rechargeGiveDao;
    @Autowired
    private PurviewService purviewService;

    @Override
    public Result<String> addRechargeConfig(RechargeConfigDTO rechargeConfigDTO) {
        if (StrUtil.isNotEmpty(rechargeConfigDTO.getRemark()) && rechargeConfigDTO.getRemark().length() > 255){
            return Result.error("备注过长");
        }
        Integer baseMoney = rechargeConfigDTO.getBaseMoney();
        Integer accountId = rechargeConfigDTO.getAccountId();
        RechargeConfig configTemplate = rechargeConfigDao.getByAccountIdAndMoney(accountId, baseMoney);
        if (Objects.nonNull(configTemplate)) {
            return Result.error("区域内已有相同金额的充值模板，请勿重复添加");
        }
        if (rechargeConfigDTO.getCouponId() != null) {
            Coupon coupon = couponService.getBycouponId(rechargeConfigDTO.getCouponId());
            if (coupon == null) {
                throw new BaseException(SystemCodeEnum.COUPON_NOT_EXIST);
            }
            if (!purviewService.purviewCheck(rechargeConfigDTO.getLoginInfo().getId(), coupon.getAccountId())) {
                throw new BaseException(SystemCodeEnum.NO_PRIVILEGE);
            }
        }
        RechargeConfig rechargeConfig = new RechargeConfig();
        rechargeConfig.setAccountId(accountId);
        rechargeConfig.setMoney(baseMoney);
        rechargeConfig.setDesc(rechargeConfigDTO.getRemark());
        rechargeConfig.setHintType(rechargeConfigDTO.getHintType());
        rechargeConfig.setStatus(rechargeConfigDTO.getStatus());
        rechargeConfig.setCreateTime(new Date());
        rechargeConfigDao.insert(rechargeConfig);
        //
        RechargeGive rechargeGive = new RechargeGive();
        rechargeGive.setAccountId(accountId);
        rechargeGive.setName(rechargeConfigDTO.getCouponName());
        rechargeGive.setBaseMoney(baseMoney);
        rechargeGive.setGiveMoney(rechargeConfigDTO.getGiveMoney());
        rechargeGive.setCouponId(rechargeConfigDTO.getCouponId());
        rechargeGive.setCouponCount(rechargeConfigDTO.getCouponCount());
        rechargeGive.setValidDays(rechargeConfigDTO.getValidDays());
        rechargeGive.setRechargeConfigId(rechargeConfig.getRechargeConfigId());
        rechargeGive.setRemark(rechargeConfigDTO.buildDetails());
        rechargeGiveDao.insertUP(rechargeGive);
        return Result.success();
    }

    @Override
    public Result<String> addCustomRechargeConfig(RechargeConfig rechargeConfig) {
        Integer accountId = rechargeConfig.getAccountId();
        Account account = accountDao.getByAccountId(accountId);
        if (account == null || account.typeIsNotUserAgent()) {
            return Result.error("非区域运营商");
        }
        RechargeConfig configTemplate = rechargeConfigDao.getByAccountIdAndMoney(accountId, -1);
        if (Objects.nonNull(configTemplate)) {
            return Result.error("区域内已有自定义充值模板，请勿重复添加");
        }
        RechargeConfig rechargeConfigNew = new RechargeConfig();
        rechargeConfigNew.setAccountId(accountId);
        rechargeConfigNew.setMoney(-1);
        rechargeConfigNew.setDesc(rechargeConfig.getDesc());
        rechargeConfigNew.setStatus(rechargeConfig.getStatus());
        rechargeConfigNew.setHintType(rechargeConfig.getHintType());
        rechargeConfigNew.setCreateTime(new Date());
        rechargeConfigDao.insert(rechargeConfigNew);
        return Result.success();
    }

    @Override
    public PageInfo<RechargeConfigVO> rechargeConfigListPage(Integer accountId, Integer status, Integer rowCount, Integer pageNo) {
        PageHelper.startPage(pageNo, rowCount);
        Map<String, Object> params = new HashMap<>(4);
        params.put("accountId", accountId);
        params.put("status", status);
        List<RechargeConfigVO> listPage = rechargeGiveDao.rechargeConfigListPage(params);
        return new PageInfo<>(listPage);
    }

    @Override
    public Result<RechargeConfigVO> selectRechargeConfigById(Integer rechargeConfigId) {
        RechargeConfigVO rechargeConfigVO = rechargeGiveDao.selectRechargeConfigById(rechargeConfigId);
        return Result.success(rechargeConfigVO);
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void deleteRechargeConfigById(Integer rechargeConfigId, LoginInfo loginInfo) {
        RechargeConfig rechargeConfig = rechargeConfigDao.selectById(rechargeConfigId);
        if (rechargeConfig != null) {
            //权限验证
            if (!purviewService.purviewCheck(loginInfo.id, rechargeConfig.getAccountId())) {
                throw new BaseException(SystemCodeEnum.NO_PRIVILEGE);
            }
            rechargeConfigDao.del(rechargeConfigId);
            rechargeGiveDao.deleteByRechargeConfigId(rechargeConfigId);
        }
    }

    @Override
    public Result<String> updateRechargeConfig(RechargeConfigDTO rechargeConfigDTO) {
        if (StrUtil.isNotEmpty(rechargeConfigDTO.getRemark()) && rechargeConfigDTO.getRemark().length() > 255){
            return Result.error("备注过长");
        }
        Integer rechargeConfigId = rechargeConfigDTO.getRechargeConfigId();
        Integer baseMoney = rechargeConfigDTO.getBaseMoney();
        Integer accountId = rechargeConfigDTO.getAccountId();
        RechargeConfig rechargeConfig = rechargeConfigDao.selectById(rechargeConfigId);
        if (Objects.isNull(rechargeConfig)) {
            return Result.error(String.format("配置id[%s]记录不存在。", rechargeConfigId));
        }
        boolean existSameAmount = rechargeConfigDao.sameAmountCheck(baseMoney, accountId, rechargeConfigId);
        if (existSameAmount) {
            return Result.error("区域内已有相同金额的充值模板，请勿重复添加");
        }
        rechargeConfig.setMoney(baseMoney);
        rechargeConfig.setDesc(rechargeConfigDTO.getRemark());
        rechargeConfig.setStatus(rechargeConfigDTO.getStatus());
        rechargeConfig.setHintType(rechargeConfigDTO.getHintType());
        rechargeConfigDao.update(rechargeConfig);

        boolean havaGive = rechargeConfigDTO.haveGive();
        RechargeGive rechargeGive = rechargeGiveDao.selectByRechargeConfigId(rechargeConfigId);
        if (Objects.isNull(rechargeGive) && havaGive) {
            //无->有
            rechargeGive = new RechargeGive();
            rechargeGive.setName(rechargeConfigDTO.getCouponName());
            rechargeGive.setAccountId(accountId);
            rechargeGive.setBaseMoney(baseMoney);
            rechargeGive.setGiveMoney(rechargeConfigDTO.getGiveMoney());
            rechargeGive.setCouponId(rechargeConfigDTO.getCouponId());
            rechargeGive.setCouponCount(rechargeConfigDTO.getCouponCount());
            rechargeGive.setValidDays(rechargeConfigDTO.getValidDays());
            rechargeGive.setRechargeConfigId(rechargeConfigId);
            rechargeGive.setRemark(rechargeConfigDTO.buildDetails());
            rechargeGiveDao.insertUP(rechargeGive);
        } else if (Objects.nonNull(rechargeGive) && havaGive) {
            //有->有
            rechargeGive.setName(rechargeConfigDTO.getCouponName());
            rechargeGive.setBaseMoney(baseMoney);
            rechargeGive.setGiveMoney(nullReturnZoro(rechargeConfigDTO.getGiveMoney()));
            rechargeGive.setCouponId(nullReturnZoro(rechargeConfigDTO.getCouponId()));
            rechargeGive.setCouponCount(nullReturnZoro(rechargeConfigDTO.getCouponCount()));
            rechargeGive.setValidDays(nullReturnZoro(rechargeConfigDTO.getValidDays()));
            rechargeGive.setRemark(rechargeConfigDTO.buildDetails());
            rechargeGiveDao.update(rechargeGive);
        } else if (Objects.nonNull(rechargeGive)) {
            //有->无
            rechargeGiveDao.delById(rechargeGive.getRechargeGiveId());
        }
        return Result.success();
    }

    public int nullReturnZoro(Integer val) {
        return Objects.isNull(val) ? 0 : val;
    }


    @Override
    public Result<String> disableRechargeConfig(Integer rechargeConfigId) {
        RechargeConfig rechargeConfig = rechargeConfigDao.selectById(rechargeConfigId);
        if (Objects.isNull(rechargeConfig)) {
            return Result.error(String.format("配置id[%s]记录不存在。", rechargeConfigId));
        }
        if (rechargeConfig.disabled()) {
            return Result.success();
        }
        rechargeConfig.setStatus(0);
        rechargeConfigDao.update(rechargeConfig);
        return Result.success();
    }

    @Override
    public Result<String> enable(Integer rechargeConfigId) {
        RechargeConfig rechargeConfig = rechargeConfigDao.selectById(rechargeConfigId);
        if (Objects.isNull(rechargeConfig)) {
            return Result.error(String.format("配置id[%s]记录不存在。", rechargeConfigId));
        }
        if (!rechargeConfig.disabled()) {
            return Result.success();
        }
        rechargeConfig.setStatus(1);
        rechargeConfigDao.update(rechargeConfig);
        return Result.success();
    }

}
